<?php





namespace app\admin\model;



use app\admin\model\Common;

use think\Exception;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\common\traits\UserInfoTrait;



/**

 * 商品model

 * Class Goods

 * @package app\shop\model

 * @author Mr.Liu

 * @create 2021-09-15 15:01

 */

class Notification extends Common

{

    use SoftDelete;

    use ActionRecordTrait,UserInfoTrait;



    /**

     * 表名

     * @var string

     */

    //protected $pk = 'id';

    protected $name = 'Notification';

    // protected $deleteTime = 'delete_time';

    protected $defaultSoftDelete = 0;

    protected $autoWriteTimestamp = true;



    // 定义时间戳字段名













    /**

     * 获取商品列表

     * 是否不分页  no_page  0/null 分页 1不分页

     * @param  array $request 请求参数

     * @return array

     * @author Mr.Li

     * @create 2021-05-26 10:51

     */

    public function getDataList(array $request): array

    {

        try {
           
            $request = $this->fmtRequest($request);
           
            $where     = $request['map'] ?? [];
           
            $where = [];
           
            $dataCount  = $this->where($where)->count();
          
            if ($dataCount>0) {
              

                $field = ['id', 'title','type', 'content','is_show','create_time'];

                $list = $this->when(!(isset($map['no_page']) && $map['no_page']) ,function($query) use ($request){

                    $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);

                })

                    ->where($where)

                    ->order('id DESC')

                    ->field($field)->select()->toArray();
               

                if ($list) {
                   
                }
            }

            $data              = [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            return $data;

        } catch (\Exception $e) {
            var_dump($e);die;

            $this->error = $e->getMessage();

            return [];

        }

    }





    /**

     * 商品详情

     * @param array $request

     * @return array

     * @author Mr.Li

     * @create 2021-09-20 16:25

     */

    public function getDataDetail(array $request): array

    {

        $goodsDetail = [];

        try {

            $id = $request['id'] ?? 0;

            if(!$id){

                $this->error = '请输入通知id';

                return [];

            }

            $informField = $request['coupon_field'] ?? '';

            if(!$informField){

                $informField = ['*'];

            }

            $detail = self::field($informField)->find($id);

            if($detail){

                $goodsDetail = $detail->toArray();

            }

            return $goodsDetail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 新增商品

     * @param  array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-05-26 11:25

     */

    public function addData(array $request): bool

    {

        try {

            // $validate = new \app\admin\validate\Goods();

            // if (!$validate->scene('create')->check($request)) {

            //     $this->error = $validate->getError();

            //     return false;

            // }

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        Db::startTrans();

        try {

            $time = time();

            // 验证

            $data = [
                'title'             => trim($request['title']),

                'type'             => isset($request['type']) ? $request['type'] :1,

                'content'       => trim($request['content']),

                'is_show'          =>  isset($request['is_show']) ? $request['is_show'] : 1,

                'create_time'   => $time,

            ];

            $this->create($data);

            Db::commit();

            $this->error = '添加成功';

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '添加失败';

        return false;



    }



    /**

     * 更新商品

     * @param array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-05-26 11:33

     */

    public function saveData(array $request): bool

    {

        // 验证

        try{

            // $validate = new \app\admin\validate\Goods();

            // if (!$validate->scene('update')->check($request)) {

            //     $this->error = $validate->getError();

            //     return false;

            // }

        }catch(\Exception $e){

            $this->error =$e->getMessage();

            return false;

        }

        $id = $request['id'] ?? 0;

        Db::startTrans();

        try {

            $goods = $this->field('id')->find($id);

            if($goods){

                $goods = $goods->toArray();

            }else{

                $this->error = '更新通知不存在';

                return false;

            }

            $time = time();

       
            $data = [

                'title'             => trim($request['title']),

                'type'             => isset($request['type']) ? $request['type'] :1,

                'content'       => trim($request['content']),

                'is_show'          =>  isset($request['is_show']) ? $request['is_show'] : 1,

            ];

            $this->where(['id'=>$id])->update($data);

            Db::commit();

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '更新失败';

        return false;

    }



    /**

     * 删除通知

     * @param  array $request 请求参数

     * @return bool

     * @author Mr.Li

     * @create 2021-05-26 15:09

     */

    public function deleteData(array $request): bool

    {

        try {



            $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];

            if (!$requestId) {

                $this->error = '参数错误';

                return false;

            }

            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);

            $where = [

                ['id', 'in', $idArr]

            ];

            Db::startTrans();

            $bool = self::where($where)->update(['is_del'=>1,'delete_time'=>time()]);

            if ($bool) {

                Db::commit();

            }else{

                Db::rollback();

                $this->error = '删除失败';

                return false;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '删除成功';

        return true;

    }



    /**

     * 更新商品的上下架状态

     * @param array $request

     * @return bool

     * @author Mr.Li

     * @create 2021-06-03 11:12

     */

    public function updateStatus(array $request): bool

    {



        $bool = false;

        $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];

        if (!$requestId) {

            $this->error = '商品id不存在';

            return false;

        }

        $status = $request['status'] ?? 0;

        if (!$status || !in_array($status,[1,2])) {

            $this->error = '上下架状态不正确';

            return false;

        }

        $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);

        $where = [

            ['id', 'in', $idArr]

        ];

        $content = '';

        try{

            if($status == 1){//上架

                $bool =  Db::name('shop_goods')->where($where)->update(['status' => 1]);

                $content .= '更新产品上下架状态：【下架】 -> 【上架】 ';

            }elseif($status == 2){//下架

                $bool = Db::name('shop_goods')->where($where)->update(['status' => 2]);

                $content .= '更新产品上下架状态：【上架】 -> 【下架】 ';

            }

            if($bool){

                foreach($idArr as $id){

                    $this->addActionRecord($request['user']['id'],'shop_goods_updateStatus',$id,$content,'shop','goods');

                }

                $this->error = '更新成功';

                return true;

            }



        }catch (\Exception $e) {

        }

        $this->error = '更新失败';

        return $bool;



    }





    /**

     * 根据条件获取信息

     * @param  array $where 查询条件

     * @param  array $field 查询字段

     * @return array

     * @author Mr.Liu

     * @create 2021-09-20 10:51

     */

    public function getGoodsList(array $where = [], array $field = []): array

    {

        try {

            $list = $this->where($where)->field($field)->select()->toArray();

        } catch (\Exception $e) {

        }



        return isset($list) && $list ? $list : [];

    }





    /**

     * 更新同步金蝶商品库存

     * @author Mr.Li

     * @create 2021-07-08 16:52

     */

    public function syncKingdeeStock()

    {

        try {



            $sqlserverConn =  \think\facade\Db::connect('sqlsrv');

            $sql = "exec proc_Dxj_kxkc 'kc'";

            //$sql = "exec DXJ_WLDWHS  'wl'";

            $sqlRes = $sqlserverConn->query($sql);

            $sqlRes = $sqlRes[0] ?? [];

            //print_r($sqlRes);

            if($sqlRes){

                foreach($sqlRes as $v){

                    $insertUnitList[$v['ckbm'].'_'.$v['Wlbm']] = [

                        'warehouse_kingdee_code'      => $v['ckbm'],

                        'goods_kingdee_code'          => $v['Wlbm'],

                        'inventory_quantity'          => $v['Dbzkxkc'],

                    ];

                }



                //获取数据库仓库库存信息

                $goodsStockData = [];

                $stockData = Db::name('shop_goods_stock')->where('id','>',0)->field('id,warehouse_kingdee_code,goods_kingdee_code,inventory_quantity')->select();

                if(!$stockData){//没有数据同步库存到数据库

                    $insertUnitList = array_values($insertUnitList);

                    if($insertUnitList){

                        Db::name('shop_goods_stock')->insertAll($insertUnitList);

                    }

                }else{//有数据开始对比 一样的更新，不一样的修改

                    foreach($stockData as $stock){

                        $stockKey = $stock['warehouse_kingdee_code'].'_'.$stock['goods_kingdee_code'];

                        if(isset($insertUnitList[$stockKey])){//存在



                            if($stock['inventory_quantity'] != $insertUnitList[$stockKey]['inventory_quantity']){

                                Db::name('shop_goods_stock')->where('warehouse_kingdee_code','=',$stock['warehouse_kingdee_code'])

                                    ->where('goods_kingdee_code','=',$stock['goods_kingdee_code'])->update(['inventory_quantity' => $insertUnitList[$stockKey]['inventory_quantity'],'update_time' => time()]);

                            }

                            unset($insertUnitList[$stockKey]);

                        }

                    }



                    //如果有新的仓库商品库存需要插入数据库

                    if(!empty($insertUnitList)){

                        $insertUnitList = array_values($insertUnitList);

                        if($insertUnitList){

                            Db::name('shop_goods_stock')->insertAll($insertUnitList);

                        }

                    }



                }



            }

            return true;



        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }



    }



    /**

     * 导入商品

     * @param $param

     * @return bool

     * @author Mr.Li

     * @create 2021-09-07 13:49

     */

    public function import($param)

    {

        // 验证

        $categoryId = 51;

        $userId = 1;

        $insertGoods = [];

        $goodsType = ['定制' => 0,'标品' => 1];

        $time = time();

        foreach($param as $v){

            $insertGoods[] = [

                'is_standard_product'       => $goodsType[$v[0]] ?? '',

                'name'                      => $v[1] ?? '',

                'desc'                      => $v[2] ?? '',

                'spec_big_name'             => $v[3] ?? '',

                'spec_small_name'           => $v[4] ?? '',

                'unit_code'                 => $v[5] ?? '',

                'small_unit_price'          => $v[6] ?? '',

                'goods_price'                     => $v[7] ?? '',

                'kingdee_stock_unit'        => $v[8] ?? '',

                'kingdee_code'              => $v[9] ?? '',

                'trans_coefficient'         => $v[10] ?? '',

                'sample_unit'               => $v[11] ?? '',

            ];

        }

        try {

            $goodsValidate = new \app\admin\validate\Goods();

            $skuValidate = new \app\admin\validate\GoodsSku();

            foreach($insertGoods as $goods){

                if (!$goodsValidate->scene('batch_create')->check($goods)) {

                    $this->error = $goodsValidate->getError();

                    return false;

                }



                if (!$skuValidate->scene('batch_create')->check($goods)) {

                    $this->error = $skuValidate->getError();

                    return false;

                }

            }



        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $unitCodes = array_column($insertGoods,'unit_code');

        if($unitCodes){

            $unitData = Db::name('shop_goods_unit')->where('big_unit_code','in',$unitCodes)->column('unit_id','big_unit_code');

        }

        $specNames = array_column($insertGoods,'spec_big_name');

        if($specNames){

            $specData = Db::name('shop_goods_spec')->where('name','in',$specNames)->column('item_id','name');

        }

        Db::startTrans();

        $time = time();

        try {

            foreach ($insertGoods as $goods){

                $unitId = $unitData[$goods['unit_code']] ?? '';

                if(!$unitId){

                    throw new \Exception('单位编码不存在,请确认是否正确');

                }

                // 验证

                $data = [

                    'name'                  => trim($goods['name']),

                    'category_id'           => $goods['is_standard_product'] ? 1 : 2 ,

                    'desc'                  => $goods['desc'],

                    'content'               => '',

                    'sort'                  => 0,

                    'thumb_image'           => '',

                    'share_image'           => '',

                    'image'                 => '',

                    'create_user_id'        =>  $userId,

                    'status'                => 1,

                    'update_time'           => $time,

                    'create_time'           => $time,

                    'is_standard_product'   => $goods['is_standard_product']

                ];

                $goodsObj = $this->create($data);

                if ($goodsObj) {

                    $this->addActionRecord(1,'shop_goods_create',$goodsObj->id,'添加商品' .$data['name'],'shop','goods');

                }

            }

            $this->error = '添加成功';

            Db::commit();

            return true;

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        return true;

    }

    public function goodsRankingList($request)
    {
        $start_time = $request['start_time'] > 0 ? $request['start_time'] : date('Y-m-1',time());
        $end_time   = $request['end_time'] > 0 ? $request['end_time'] : date('Y-m-t',time());

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time)+86399;

        $where = [];

        array_push($where,['status','=','2']);
        array_push($where,['create_time','between',"$start_time,$end_time"]);

        if($request['shop_id']){
            array_push($where,['shop_id','=',$request['shop_id']]);
        }

        if($request['shop_ids']){
            array_push($where,['shop_id','in',$request['shop_ids']]);
        }

        if($request['market_id']){
            $shopList = Db::name('shop')->where('market_id',$request['market_id'])->column('shop_id');
            array_push($where,['shop_id','in',$shopList]);
        }

        $order_ids = Db::name('shop_order')->where($where)->column('id');

        
        $goodsList = Db::name('shop_goods')->where('is_ranking','1')->column('kingdee_code');

        $where = [];

        array_push($where,['kingdee_code','in',$goodsList]);

        $res = Db::name('shop_order_goods')->where($where)->group('kingdee_code')->order('amount DESC')->column('sum(pay_price*number) as amount','kingdee_code');
        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;
        $NO = 1;
        $list = [];
        foreach ($res as $key => $value) {

            $one = [];

            $goodInfo = Db::name('shop_goods')->where('kingdee_code',$key)->find();

            $one['NO'] = $NO;
            $one['name'] = $goodInfo['name'];
            $one['kingdee_code'] = $goodInfo['kingdee_code'];
            $one['sum'] = sprintf("%.2f", $value);

            array_push($list,$one);

            $NO++;
        }

        // array_multisort($amount,SORT_DESC,$list);

        return $list;

        
    }

}

